<template>
  <el-card>
    <template #header>账号列表</template>

    <div>
      <!-- 1.0 数据列表的渲染 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        size="mini"
        @selection-change="handleSelectionChange"
      >
        <!-- label 列标题  prop  表格数据  -->
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="account" label="账号"> </el-table-column>
        <el-table-column prop="userGroup" label="用户组"> </el-table-column>
        <el-table-column label="创建时间">
          <!-- 作用域插槽,解构当前行的row -->
          <template v-slot="{ row }">
            {{ row.ctime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="default" size="mini" @click="showCurUser(row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="delUser(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 2.0 分页显示 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 3.0 操作按钮 -->
      <div>
        <el-button type="danger" size="mini" @click="delAll"
          >批量删除</el-button
        >
        <el-button type="primary" size="mini" @click="toggleSelection()"
          >取消选择</el-button
        >
      </div>

      <!-- 4.0 编辑状态框 -->
      <el-dialog title="账号编辑" :visible.sync="dialogVisible" width="50%">
        <div>
          <!-- 4.1 用于放置表单布局 -->
          <el-form
            :model="editForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            size="mini"
          >
            <el-form-item label="账号" prop="account">
              <el-input
                type="text"
                v-model="editForm.account"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户组" prop="userGroup">
              <el-select v-model="editForm.userGroup" placeholder="请选择">
                <el-option label="超级管理员" value="超级管理员"> </el-option>
                <el-option label="普通管理员" value="普通管理员"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogVisible = false"
            >取 消</el-button
          >
          <el-button size="mini" type="primary" @click="checkEdit('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { validateAccount } from '@/utils/validate.js'
import {
  accountList,
  accountDel,
  accountDelAll,
  accountEdit
} from '@/api/users.js'

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      total: 0,
      // 表格的数据
      tableData: [],
      // 选中的表格数据
      multipleSelection: [],
      dialogVisible: false,
      // 用于回写的数据对象
      editForm: {
        account: '',
        userGroup: ''
      },
      rules: {
        account: [{ validator: validateAccount, trigger: 'blur' }],
        userGroup: [
          // required 必须的    trigger  触发
          { required: true, message: '请选择用户组', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // 页面一上来需要请求的函数在这里调用
    this.getData()
  },
  methods: {
    async getData() {
      const { data, total } = await accountList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      this.tableData = data
      this.total = total
      // console.log(data)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getData()
    },
    // 只要选择了前面的列,就会把对应的数据扔到数组中
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    delUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 在这里发起请求
          const { code } = await accountDel({ id })
          // console.log(data)
          if (code === 0) {
            this.getData()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 批量删除
    delAll() {
      if (this.multipleSelection.length === 0) return ''
      this.$confirm('此操作将永久删除这些用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // console.log(this.multipleSelection)
          const ids = this.multipleSelection.map(item => item.id)
          // 在这里发起请求
          const { code } = await accountDelAll({
            ids: JSON.stringify(ids)
          })
          // console.log(data)
          if (code === 0) {
            this.getData()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 展示当前用户
    showCurUser(row) {
      // 把当前行的数据赋值给显示的修改表单
      this.editForm = { ...row }
      this.dialogVisible = true
    },
    checkEdit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const { code } = await accountEdit(this.editForm)
          // console.log(data)
          if (code === 0) {
            this.dialogVisible = false
            this.getData()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
  // filters: {
  //   dateFormat(time) {
  //     return moment(time).format('YYYY-MM-DD HH:mm:ss')
  //   }
  // }
}
</script>

<style lang="less" scoped>
.el-input,
.el-select {
  width: 197px;
}
</style>
